<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use think\Model;

use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;
use PHPExcel_Cell_DataType;
//部门管理模块
class Departments extends Common
{
    //部门导出
    public function bumendaochu(){
        $dep=db("department d")->join("employee e","d.principal=e.id","LEFT")->join("department dp","d.parent_id=dp.id","LEFT")
        ->where("d.is_deleted=0")->order("d.index")
        ->field("d.de_name,e.em_name,dp.de_name as parent,d.remark,d.id")->select();
        $eid = Session::get("employee_id");
        $users = Db::table("employee")->where(["id" => $eid])->find();

        Vendor("PHPExcel");


        Vendor("PHPExcel.Writer.Excel5");

        // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new PHPExcel();


        $objProps = $objPHPExcel->getProperties();

        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");

        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("部门列表");

        #################总标题

        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:E1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1', "部门列表");
        //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14);
        #################表头信息
        $objPHPExcel->getActiveSheet()->mergeCells('A2:E2');
        $objPHPExcel->getActiveSheet()->setCellValue('A2', "(本表单由软件导出，导出时间：" . date("Y-m-d H:i:s") . "；导出人：{$users["em_name"]})");
        //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('3')->getAlignment()->setWrapText(true);
        
         $objPHPExcel->getActiveSheet()->getStyle('A3:E3')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
         $objPHPExcel->getActiveSheet()->getStyle('A3:E3')->getFill()->getStartColor()->setARGB('0099CCFF');
             //水平剧中
         $objPHPExcel->getActiveSheet()->getStyle('A3:E3')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
         $objPHPExcel->getActiveSheet()->getStyle('A3:E3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $objPHPExcel->getActiveSheet()->setCellValue('A3',"序号");
        $objPHPExcel->getActiveSheet()->setCellValue('B3',"部门名称");
        $objPHPExcel->getActiveSheet()->setCellValue('C3',"部门第一负责人");
        $objPHPExcel->getActiveSheet()->setCellValue('D3',"上级部门");
        $objPHPExcel->getActiveSheet()->setCellValue('E3',"说明");
         $h=3;
        for($i=0;$i<count($dep);$i++){
            $h++;
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$h,$i+1,PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('B'.$h,$dep[$i]["de_name"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('C'.$h,$dep[$i]["em_name"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('D'.$h,$dep[$i]["parent"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('E'.$h,$dep[$i]["remark"],PHPExcel_Cell_DataType::TYPE_STRING);
            
        }
         $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
            $objPHPExcel->getActiveSheet()->getStyle('A1:E'.$h)->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪
        //设置宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
           
        //var_dump($objWriter);exit;
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=file.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }
    public function huishoucz($id){
        $de=db("department")->where(["id"=>$id])->find();
        $pid=$de["parent_id"];
        if($pid){
            $par=db("department")->where(["id"=>$pid])->find();
        }else{
            $par=[];
        }
       
        if($par){
            if($par["is_deleted"]){
                return json_encode(["msg"=>"存在未恢复的上级部门，请优先处理","state"=>2]);
            }
        }
        try{
            db("department")->where(["id"=>$id])->update(["is_deleted"=>0]);
        }catch(\Exception $e){
            return json_encode(["msg"=>"系统繁忙，请稍后","state"=>2]);
        }
        return json_encode(["msg"=>"","state"=>1]);
    }
    public function huishou($page=1,$list=10){
        $sum=db("department")->where("is_deleted=1")->count();
        $maxpage=ceil($sum/$list);
        $page=$page<$maxpage?$page:$maxpage;
        $page=$page>1?$page:1;

        $start=($page-1)*$list;
        $dep=db("department d")->join("employee e","d.principal=e.id","LEFT")->join("department dp","d.parent_id=dp.id","LEFT")
        ->where("d.is_deleted=1")->limit($start,$list)->order("d.index")
        ->field("d.de_name,e.em_name,dp.de_name as parent,d.remark,d.id")->select();
        $this->assign("dep",$dep);
        $this->assign("sum",$sum);
        $this->assign("page",$page);
        $this->assign("list",$list);
        $this->assign("maxpage",$maxpage);
        return $this->fetch();
    }
    public function shanchucz($id){
        Db::startTrans();
        try{
            db("department_employee")->where("department_id=$id")->delete();
            db("department")->where(["id"=>$id])->update(["is_deleted"=>1]);
        }catch(\Exception $e){
            Db::rollBack();
            return 2;
        }
        Db::commit();
        return 1;
    }
    public function shanchu($id){
        //查询是否有未删除的下级
        $has=db("department")->where("path like '%[{$id}]%' and is_deleted=0")->find();
        if($has){
            return json_encode(["msg"=>"存在未删除的下级部门,请先行处理","state"=>2]);
        }
        //查询是否存在员工
        $em=db("department_employee de")->join("employee e","de.employee_id=e.id")->where("de.department_id=$id and de.`index`=1 and e.is_deleted=0")->find();
        if($em){
            return json_encode(["msg"=>"该部门下尚存在员工,请先行处理","state"=>2]);
        }
        return json_encode(["msg"=>"","state"=>1]);
    }
	//部门管理
	//$de_name查询部门名
	public function manage($de_name="",$check_type='1',$page=1,$list=10){
		$de_name=trim($de_name);
		
		//echo $list;
		$depart_model=model('Department');
		//查询条件
		
    	$where="d.is_actived=1 and d.is_deleted=0 ";

    	$alldepart=Db::table("department")->alias("d")->where($where)->order("index")->field("id,parent_id as pId,de_name as name")->select();
    	$this->assign("alldepart",json_encode($alldepart));
    	//数据总量
    	$sum=0;
        $maxpage=0;
        $page=$page>1?$page:1;
    	if($de_name){
    		//获取查询部门的编号
    		$datawhere["is_actived"]=1;$datawhere["is_deleted"]=0;$datawhere["de_name"]=$de_name;

    		$thisdipart=$depart_model->get_this_department($datawhere);
    		if($thisdipart){
    			switch ($check_type) {
    			case '1':
    				$where.="and (d.id={$thisdipart["id"]} or d.path like '%[{$thisdipart["id"]}]%')";
    				
    				break;
    			case '2':
    				$where.="and d.id={$thisdipart["id"]} ";
    				break;
    			case '3':
    				$where.="and d.path like '%[{$thisdipart["id"]}]%'";
    				break;
    			
    			}
    			$sum=Db::table("department")->alias("d")->where($where)->count();
                $maxpage=ceil($sum/$list);$page=$page<$maxpage?$page:$maxpage;
    			$depart_arr=$depart_model->get_department_list($where,$page,$list);
    		}else{
    			$depart_arr=[];
    		}
    		
    	}else{
    		//查询所有部门列表
    		$sum=Db::table("department")->alias("d")->where($where)->count();
            $maxpage=ceil($sum/$list);$page=$page<$maxpage?$page:$maxpage;
			$depart_arr=$depart_model->get_department_list($where,$page,$list);
    	}
		
		$this->assign("depart_arr",$depart_arr);
		$this->assign("de_name",$de_name);
		$this->assign("check_type",$check_type);
		$this->assign("sum",$sum);
		$this->assign("page",$page);
		$this->assign("list",$list);
		$this->assign("maxpage",$maxpage);
		return $this->fetch('manage');
	}
	
	//查询员工列表
	public function getem(){
	       $departs=Db::table("department")->where(["is_actived"=>1,"is_deleted"=>0])
           ->field("id,parent_id as pId,de_name as name")->select();
           $employees=Db::table("employee")->alias("e")
           ->join("department_employee de","e.id=de.employee_id")
           ->join("department d","de.department_id=d.id")
           ->where(["e.is_actived"=>1,"d.is_actived"=>1,"e.is_deleted"=>0,"d.is_deleted"=>0,"de.index"=>1])
           ->field("e.id as id,d.id as pId,e.em_name as name")
           ->select();
           $result=[];
           for($i=0;$i<count($departs);$i++){
                $result[$i]["id"]=$departs[$i]["id"];
                $result[$i]["pId"]=$departs[$i]["pId"];
                $result[$i]["name"]=$departs[$i]["name"];

                $result[$i]["chkDisabled"]=true;
                 $result[$i]["nocheck"]=true;
               // $result[$i]["icon"]=ROOT_PATH."/public/static/zTreeStyle/img/diy/1_close.png";
               
           }
           
           for($i=0;$i<count($employees);$i++){
                $result[$i+count($departs)]["eid"]=$employees[$i]["id"];
                $result[$i+count($departs)]["pId"]=$employees[$i]["pId"];
                $result[$i+count($departs)]["name"]=$employees[$i]["name"];
                //$result[$i+count($departs)]["icon"]="./../../static/zTreeStyle/img/diy/3.png";
           }
           return json_encode($result);
	}
    //查询所有部门
    public function getbm($did=-10,$pid=0){
         $departs=Db::table("department")->where(["is_actived"=>1,"is_deleted"=>0])
           ->field("id,parent_id as pId,de_name as name,path")->select();
            $result=[];
           for($i=0;$i<count($departs);$i++){
                $result[$i]["id"]=$departs[$i]["id"];
                $result[$i]["pId"]=$departs[$i]["pId"];
                $result[$i]["name"]=$departs[$i]["name"];

                if($result[$i]["id"]==$pid){
                     $result[$i]["checked"]=true;
                }
                $result[$i]["open"]=true;

                 if($departs[$i]["path"]){
                    $arr=explode('[',$departs[$i]["path"]);
                    $str=implode('',$arr);
                    $notp=explode("]",$str);
                    //return $arr;
                   // print_r($notp);//exit;
                }else{
                    $notp=[];
                }
                if($result[$i]["id"]==$did||in_array($did,$notp)){
                     $result[$i]["chkDisabled"]=true;
                }
           }
           
         
           return json_encode($result);

    }
    //查询除自身以外部门以及判断部门是否已经被选中
    public function getobm(){
        $request=Request::instance();
        $data=$request->post();
        //$deid=1;$deids="1,2,3";
        $deid=$data["deid"];
        $deids=$data["odeids"];
        //echo $deids;exit;
         $deidsarr=[];
        if($deids){
            $deidsarr=explode(',',$deids);
        }
         $departs=Db::table("department")->where(["is_actived"=>1,"is_deleted"=>0])
           ->field("id,parent_id as pId,de_name as name")->select();
            $result=[];
         for($i=0;$i<count($departs);$i++){
                $result[$i]["id"]=$departs[$i]["id"];
                $result[$i]["pId"]=$departs[$i]["pId"];
                $result[$i]["name"]=$departs[$i]["name"];
                if($departs[$i]["id"]==$deid){
                    $result[$i]["chkDisabled"]=true;
                }
                if(in_array($result[$i]["id"],$deidsarr)){
                     $result[$i]["checked"]=true;
                }
                $result[$i]["open"]=true;
           }
           
         
           return json_encode($result);
    }
    //创建或修改部门
    public function editorcreate(){
         //isupdate更新或创建
            //new_de_name部门名称
            //principal负责人
            //index次序
            //parent_id
            //is_sale
            //remark
            $request = Request::instance();
            $data=$request->post();//接收数据
            $isupdate=$data["isupdate"];
            $newdata["de_name"]=htmlspecialchars(trim($data["dename"])) ;
            $newdata["principal"]=trim($data["principal"]);
            $newdata["index"]=trim($data["index"]);
            if(trim($data["pid"]))
                $newdata["parent_id"]=trim($data["pid"]);
            else
                $newdata["parent_id"]=null;
            $newdata["is_sale"]=trim($data["is_sale"]);
            $newdata["remark"]=htmlspecialchars(trim($data["remark"]));
            //如果存在上级查询上级的path
             if($newdata["parent_id"]){
                $pNode=Db::table("department")->where("id={$newdata["parent_id"]}")->field("path")->find();
                 $newdata["path"]=$pNode["path"]."[{$newdata["parent_id"]}]";
             }else{
                $newdata["path"]=null;
             }

           

            if($newdata["de_name"]){
                if($newdata["index"]){
                    
                    if($isupdate==0){
                        $ischongfu=Db::table("department")->where("de_name='{$newdata["de_name"]}'")->find();
                        if($ischongfu){
                            return 5;
                        }else{
                             Db::startTrans(); //开启事物
                               $newdata["created_on"]=date("Y-m-d H:i:s");

                               try{
                                $res1=Db::table("department")->insertGetId($newdata);
                                //为负责人创建部门身份
                                $dec=Db::table("department_employee")->where(["employee_id"=>$newdata["principal"]])->count();
                                //获取此人拥有的所有部门
                                if($dec){
                                    $dataadd_d_e["index"]=2;
                                }else{
                                    $dataadd_d_e["index"]=1;
                                }
                                $dataadd_d_e["employee_id"]=$newdata["principal"];$dataadd_d_e["department_id"]=$res1;
                                db("department")->query("update department set `index`=`index`+1 where `index`>={$newdata["index"]}");
                                $res2=Db::table("department_employee")->insert($dataadd_d_e);

                               }catch(\Exception $e){

                                    Db::rollBack();
                                    return $e->getMessage();
                               }
                               if($res1){
                                   Db::commit(); //事物提交
                                   return 1;//成功
                               }else{
                                    Db::rollBack();
                                    return 4;//失败
                               }
                        }
                      
                    }else{
                        if($isupdate==$newdata["parent_id"]){
                            echo 6;//上级部门不能是本部门
                        }else{
                             $ischongfu=Db::table("department")->where("de_name='{$newdata["de_name"]}' and id<>{$isupdate}")->find();
                                if($ischongfu){
                                return 5;
                             }
                             //获取自身原先path
            $yuan=Db::table("department")->where("id={$isupdate}")->find();
            $oldpath=$yuan["path"];
            //return $oldpath;
                               Db::startTrans(); //开启事物
                            // $newdata["id"]=$isupdate;
                            $newdata["modifiled_on"]=date("Y-m-d H:i:s");
                            //print_r($newdata);exit;

                            try{
                                db("department")->query("update department set `index`=`index`-1 where `index`>={$yuan["index"]}");
                                db("department")->query("update department set `index`=`index`+1 where `index`>={$newdata["index"]}");
                                $res1=Db::table("department")->where("id",$isupdate)->update($newdata);

                                $dec=Db::table("department_employee")->where(["employee_id"=>$newdata["principal"],"department_id"=>$isupdate])->count();
                                //print_r($res1);exit;
                                if($dec){
                                    $res2=1;
                                }else{

                                        $dataadd_d_e["index"]=2;
                                      
                                        $dataadd_d_e["employee_id"]=$newdata["principal"];$dataadd_d_e["department_id"]=$isupdate;
                                        $res2=Db::table("department_employee")->insert($dataadd_d_e);
                                }
                                //下级部门path修改
                                $xiaji=Db::table("department")->where("path like '%[{$isupdate}]%'")->select();
                                $check=0;
                                for($i=0;$i<count($xiaji);$i++){
                                    if($oldpath){
                                         $tmparr["path"]=str_replace($oldpath,$newdata["path"],$xiaji[$i]["path"]);
                                     }else{
                                         $tmparr["path"]=$newdata["path"].$xiaji[$i]["path"];
                                     }
                                   
                                    $tmparr["modifiled_on"]=date("Y-m-d H:i:s") ;
                                     $tmparr["id"]=$xiaji[$i]["id"];

                                     
                                    $tmpres=Db::table("department")->update($tmparr);
                                    if($tmpres)
                                        $check++;

                                }
                                if($check==count($xiaji))
                                        $res3=1;
                                    else
                                        $res3=0;
                            }
                            catch(\Exception $e){

                                        Db::rollBack();
                                        return 41;
                            }
                            if($res1&$res2&$res3){
                                       Db::commit(); //事物提交
                                       return 1;//成功
                                   }else{
                                        Db::rollBack();
                                        return 42;//失败
                                   }

                            }
                            //更新
                      

                    }
                }else{
                    return 2;//次序空
                }
            }else{
                return 3;//部门名不通过
            }
    }
    //导入部门
    public function import(){
        return $this->fetch();
    }
    public function upload(){
        // 获取表单上传文件
        $file = request()->file('file');
        if($file){
                $info = $file->validate(['size'=>2*1024*1024,'ext'=>'xls'])->move(ROOT_PATH . 'public/uploads/bumen' . DS );
                if($info){
                    // 成功上传后 获取上传信息
                   
                    // 输出
                    $savename= $info->getSaveName();
                    $path=ROOT_PATH . 'public/uploads/bumen/'.$savename;

                    $res=$this->bumenexcel_chuli($path);

                    return $res;
                    
                }else{
                    // 上传失败获取错误信息
                    return json_encode(["msg"=>$file->getError(),"state"=>2]);
                   
                }
            }else{
                $res=["state"=>2,"msg"=>"文件不能为空"];
                return json_encode($res);
            }
    }
    public function bumenexcel_chuli($filename){
        //return json_encode(["msg"=>"部门名称不能为空","state"=>2]);
        Db::startTrans(); //开启事物
        Vendor("PHPExcel");
        Vendor("PHPExcel.IOFactory");
        
        Vendor("PHPExcel.Reader.Excel5");
        //$filename=ROOT_PATH . 'public/a.xls';
        $objReader = PHPExcel_IOFactory::createReaderForFile($filename);
        $objPHPExcel = $objReader->load($filename);
        $sheet=$objPHPExcel->setActiveSheetIndex(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumm = $sheet->getHighestColumn(); // 取得总列数
        for ($row = 4; $row <= $highestRow; $row++){//行数是以第1行开始
            if(!trim($sheet->getCell('A'.$row)->getValue())){
                break;
            }
            $tmpbumen=[];
            for ($column = 0; $column < 7; $column++) {
                $c=chr($column+65);//echo $c;exit;
                $content=trim($sheet->getCell($c.$row)->getValue());

                switch ($column) {
                    case 0:
                        # 部门名称
                        if($content){
                            $iscf=db("department")->where(["de_name"=>$content])->count();
                            if($iscf){
                                Db::rollBack();unlink($filename);
                                return json_encode(["msg"=>"部门{$content}已存在","state"=>2]);
                            }else{
                                $tmpbumen["de_name"]=$content;
                            }
                        }else{
                            Db::rollBack();unlink($filename);
                            return json_encode(["msg"=>"部门名称不能为空","state"=>2]);
                        }
                        break;
                    case 1:
                        # 部门编号
                        if($content){
                            $iscf=db("department")->where(["de_no"=>$content])->count();
                            if($iscf){
                                Db::rollBack();unlink($filename);
                                return json_encode(["msg"=>"部门编号{$content}已存在","state"=>2]);
                            }else{
                                $tmpbumen["de_no"]=$content; 
                            }
                            
                        }else{
                           $tmpbumen["de_no"]=null; 
                        }
                        break;
                    case 2:
                        # 部门第一负责人
                        if($content){
                            $fuzeren=db("employee")->where(["em_name"=>$content])->value("id");
                            if($fuzeren){
                                $tmpbumen["principal"]=$fuzeren;
                            }else{
                                Db::rollBack();unlink($filename);
                                return json_encode(["msg"=>"部门负责人{$content}不存在","state"=>2]);
                            }
                        }else{
                            $tmpbumen["principal"]=null;
                        }
                        break;
                    case 3:
                        # 显示次序
                        if($content){
                            $tmpbumen["index"]=$content;
                        }else{
                            Db::rollBack();unlink($filename);
                            return json_encode(["msg"=>"显示次序不能为空","state"=>2]);
                        }
                        break;
                    case 4:
                        # 上级部门
                        if($content){
                            $parent_id=db("department")->where(["de_name"=>$content])->value("id");
                            if($parent_id){
                                $tmpbumen["parent_id"]=$parent_id;
                                $path=db("department")->where(["de_name"=>$content])->value("path");
                                $path.="[{$parent_id}]";
                                $tmpbumen["path"]=$path;
                            }else{
                                Db::rollBack();unlink($filename);
                                return json_encode(["msg"=>"上级部门{$content}不存在","state"=>2]);
                            }
                        }else{
                            $tmpbumen["parent_id"]=0;
                            $tmpbumen["path"]=null;
                        }
                        break;
                    case 5:
                        # 是否销售部门
                        if($content){
                            if($content=="是"){
                                $tmpbumen["is_sale"]=1;
                            }else if($content=="否"){
                                $tmpbumen["is_sale"]=0;
                            }else{
                                Db::rollBack();unlink($filename);
                                return json_encode(["msg"=>"是否销售部门不能为空","state"=>2]);
                            }
                        }else{
                            Db::rollBack();unlink($filename);
                            return json_encode(["msg"=>"是否销售部门不能为空","state"=>2]);
                        }
                        break;
                    case 6:
                        # 说明
                        if($content){
                            $tmpbumen["remark"]=$content;
                        }else{
                            $tmpbumen["remark"]=null;
                        }
                        break;
                    
                }
            }
            $tmpbumen["created_on"]=date("Y-m-d H:i:s");$tmpbumen["created_on"]=date("Y-m-d H:i:s");$tmpbumen["is_actived"]=1;$tmpbumen["is_deleted"]=0;
            db("department")->query("update department set `index`=`index`+1 where `index`>={$tmpbumen["index"]}");
            db("department")->insert($tmpbumen);

        }
        Db::commit();
        unlink($filename);
        return json_encode(["msg"=>"","state"=>1]);
    }
    //导入负责人
    public function fuzeren(){
        return $this->fetch();
    }
    public function uploadfuze(){
        // 获取表单上传文件
        $file = request()->file('file');
        if($file){
                $info = $file->validate(['size'=>2*1024*1024,'ext'=>'xls'])->move(ROOT_PATH . 'public/uploads/bumen' . DS );
                if($info){
                    // 成功上传后 获取上传信息
                   
                    // 输出
                    $savename= $info->getSaveName();
                    $path=ROOT_PATH . 'public/uploads/bumen/'.$savename;

                    $res=$this->fuzerenexcel_chuli($path);

                    return $res;
                    
                }else{
                    // 上传失败获取错误信息
                    return json_encode(["msg"=>$file->getError(),"state"=>2]);
                   
                }
            }else{
                $res=["state"=>2,"msg"=>"文件不能为空"];
                return json_encode($res);
            }
    }
    public function fuzerenexcel_chuli($filename){
        Db::startTrans(); //开启事物
        Vendor("PHPExcel");
        Vendor("PHPExcel.IOFactory");
        
        Vendor("PHPExcel.Reader.Excel5");
        //$filename=ROOT_PATH . 'public/a.xls';
        $objReader = PHPExcel_IOFactory::createReaderForFile($filename);
        $objPHPExcel = $objReader->load($filename);
        $sheet=$objPHPExcel->setActiveSheetIndex(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumm = $sheet->getHighestColumn(); // 取得总列数
        for ($row = 4; $row <= $highestRow; $row++){//行数是以第1行开始
            if(!trim($sheet->getCell('A'.$row)->getValue())){
                break;
            }
            for ($column = 0; $column < 2; $column++) {
                $c=chr($column+65);//echo $c;exit;
                $content=trim($sheet->getCell($c.$row)->getValue());
                
                if($column==0){
                    if($content){
                        $bumen=db("department")->where(["de_name"=>$content])->value("id");
                        if($bumen){
                            $id=$bumen;
                        }else{
                            Db::rollBack();unlink($filename);
                            return json_encode(["msg"=>"不存在部门:{$content}","state"=>2]);
                        }
                    }else{
                        Db::rollBack();unlink($filename);
                        return json_encode(["msg"=>"部门名称不能为空","state"=>2]);
                    }
                    
                }else{
                    if($content){
                        $em=db("employee")->where(["em_name"=>$content])->value("id");
                        if($em){
                            $tmpbumen["principal"]=$em;
                        }else{
                            Db::rollBack();unlink($filename);
                            return json_encode(["msg"=>"不存在员工:{$content}","state"=>2]);
                        }
                    }else{
                        Db::rollBack();unlink($filename);
                        return json_encode(["msg"=>"部门第一负责人不能为空","state"=>2]);
                    }
                }
            }
            db("department")->where("id=$id")->update($tmpbumen);
        }
        Db::commit();
        unlink($filename);
        return json_encode(["msg"=>"","state"=>1]);
    }
}
